﻿using Gadgeteer.Modules.GHIElectronics;
using Gadgeteer.Modules.Seeed;
using GeoBox.BoxApplication.CellularRadioDriver;
using GeoBox.BoxApplication.JSON;
using GeoBox.BoxApplication.Shared;
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;

namespace GeoBox.BoxApplication
{
    class GeoBoxLocator
    {
        private readonly SDCard _sdCard;
        private readonly GPS _gps;
        private readonly AzureClient _client;
        private GPS.Position lastPosition;
        private Thread _sendThread;

        public GeoBoxLocator(GPS gps, CellularRadioManager cellularRadio, SDCard sdCard)
        {
            _sdCard = sdCard;
            _gps = gps;
            _client = new AzureClient(cellularRadio);

            _sendThread = new Thread(SendPoints);
            _sendThread.Start();
            _gps.DebugPrintEnabled = true;
        }


        private void SendPoints()
        {
            while (true)
            {
                try
                {
                    if (!_client.IsReady)
                        continue;

                    var position = lastPosition;
                    lastPosition = null;
                    TransmitPosition(position);
                }
                catch 
                {
                }
                finally
                {
                    Thread.Sleep(5000);
                }
            }
        }

        public void StartLocatingBox()
        {
            this._gps.PositionReceived += _gps_PositionReceived;
        }

        public void StopLocationBox()
        {
            this._gps.PositionReceived -= _gps_PositionReceived;
        }

        void _gps_PositionReceived(GPS sender, GPS.Position position)
        {
            lastPosition = position;
        }

        private bool TransmitPosition(GPS.Position position)
        {
            Debug.Print("TransmitPosition was called");
            var obj = new JsonObject();
            obj.Add("Id", Device.DeviceId);

            if (position != null)
            {
                var lastLocation = new JsonObject();

                lastLocation.Add("UtcTime", position.FixTimeUtc);
                lastLocation.Add("Latitude", position.Latitude);
                lastLocation.Add("Longitude", position.Longitude);

                obj.Add("LastLocation", lastLocation);
            }

            var res = _client.PostJson("/Device", obj.ToString());
            return res;
        }
    }
}
